<template>
  <el-container class="advance-query-form advance-box" style="position: relative;">
    <el-aside width="300px">
      <el-card class="base-card" shadow="never">
        <template #header>
          <div class="base-card-header">
            <span style="color: #333333; font-weight: bold" class="header-title">所属校区</span>
            <div class="base-card-operation">
              <el-button
                class="advance-icon-btn"
                style="width: 40px; height: 32px; padding: 0"
                @click="refreshSchoolIdDropdownList"
              >
                <img src="@/assets/img/refresh2.png" alt="" style="vertical-align: middle" />
              </el-button>
            </div>
          </div>
        </template>
        <el-scrollbar :style="{height: (mainContextHeight - 130) + 'px'}" class="custom-scroll">
          <el-tree
            ref="schoolId"
            :props="{label: 'name'}"
            :data="schoolIdWidget.dropdownList"
            node-key="id"
            current-node-key="id"
            :highlight-current="true"
            :default-expand-all="true"
            @node-click="onSchoolIdValueChange"
          />
        </el-scrollbar>
      </el-card>
    </el-aside>
    <el-main class="page-box" style="padding-left: 15px; display: flex">
    <el-form
      ref="formClassAdvanceAIRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="90px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormClassAdvanceAI()" @reset="resetFormClassAdvanceAI">
        <el-form-item label="班级名称">
          <el-input
            class="filter-item"
            v-model="formFilter.classNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="班级级别">
          <el-select
            class="filter-item"
            v-model="formFilter.classLevelFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="classLevelFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in classLevelFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            class="filter-item"
            v-model="formFilter.createTimeFilter"
            type="daterange"
            start-placeholder=""
            end-placeholder=""
            :clearable="true"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[new Date().setHours(0, 0, 0, 0), new Date().setHours(23, 59, 59, 999)]"
          />
        </el-form-item>
      </filter-box>
    </el-form>
      <table-box
        ref="studentClass"
        class="page-table"
        :data="studentClassWidgetDataList"
        :size="layoutStore.defaultFormItemSize"
        :row-config="{isCurrent: false, isHover: true}"
        :seq-config="{startIndex: ((studentClassWidgetCurrentPage - 1) * studentClassWidgetPageSize)}"
        :sort-config="{remote: true}"
        :hasExtend="true"
        rowKey="classId"
        :inlineRules="studentClassInline.inlineRules"
        @sort-change="studentClassWidget.onSortChange"
        @refresh="studentClassWidget.refreshTable()"
        @change="onStudentClassSelectionChange"
      >
        <template #operator>
          <el-button
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click="onAddStudentclassClick()"
            >
            行内添加
          </el-button>
          <el-button
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click="onFormAddClassAIClick()"
            >
            新建班级
          </el-button>
          <el-upload
            class="btn-import"
            :auto-upload="false"
            action=""
            :show-file-list="false"
            accept=".xls,.xlsx"
            style="display: inline-block;"
            :on-change="onImportClick"
          >
            <template #trigger>
              <el-button
                type="primary"
                :size="layoutStore.defaultFormItemSize"
              >
                导入
              </el-button>
            </template>
          </el-upload>
          <el-button
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click="onExportClick()"
            >
            导出
          </el-button>
          <el-button
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click="onBatchDeleteClick()"
            >
            批量删除
          </el-button>
        </template>
        <vxe-column fixed="left" type="checkbox" :width="40" />
        <vxe-column title="序号" type="seq" fixed="left" :index="studentClassWidget.getTableIndex" :width="80" />
        <vxe-column title="班级名称" field="className" />
        <vxe-column title="所属校区" field="schoolIdDictMap.name" />
        <vxe-column title="班级级别" field="classLevelDictMap.name" />
        <vxe-column title="总课时数" field="totalClassHours" />
        <vxe-column title="创建时间" field="createTime">
          <template v-slot="scope">
            <span>{{formatDateByStatsType(scope.row.createTime, 'day')}}</span>
          </template>
        </vxe-column>
        <table-box-inline-auto-save-column
          v-if="studentClassInline.supportAutoNext"
          @save="row => onSaveStudentClassInlineRow(row, true)"
        />
        <vxe-column title="操作" fixed="right">
          <template v-slot="scope">
            <template v-if="!studentClass.isRowEditing(scope.row)">
              <el-button
                link
                type="primary"
                :size="layoutStore.defaultFormItemSize"
                @click.stop="onFormEditClassAIClick(scope.row)"
                :disabled="studentClass.isTableEditing()"
              >
                编辑班级
              </el-button>
              <el-button
                link
                type="primary"
                :size="layoutStore.defaultFormItemSize"
                @click.stop="onEditStudentclassClick(scope.row)"
                :disabled="studentClass.isTableEditing()"
              >
                行内编辑
              </el-button>
              <el-button
                link
                type="primary"
                :size="layoutStore.defaultFormItemSize"
                @click.stop="onDeleteClick(scope.row)"
                :disabled="studentClass.isTableEditing()"
              >
                删除
              </el-button>
            </template>
            <template v-else>
              <el-button
                link
                type="primary"
                :size="layoutStore.defaultFormItemSize"
                key="studentClassSaveTable"
                @click.stop="onSaveStudentClassInlineRow(scope.row, false)"
              >
                保存
              </el-button>
              <el-button
                link
                type="primary"
                :size="layoutStore.defaultFormItemSize"
                key="studentClassSaveTable"
                @click.stop="onCancelStudentClassInlineRow(scope.row)"
              >
                取消
              </el-button>
            </template>
          </template>
        </vxe-column>
        <template slot="empty">
          <div class="table-empty unified-font">
            <img src="@/assets/img/empty.png">
            <span>暂无数据</span>
          </div>
        </template>
        <!-- 分页 -->
        <template #pagination>
          <el-row type="flex" justify="end" style="margin-top: 10px;">
            <el-pagination
              :total="studentClassWidgetTotalCount"
              :current-page="studentClassWidgetCurrentPage"
              :page-size="studentClassWidgetPageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, prev, pager, next, sizes"
              @current-change="studentClassWidget.onCurrentPageChange"
              @size-change="studentClassWidget.onPageSizeChange">
            </el-pagination>
          </el-row>
        </template>
      </table-box>
      <label v-if="subPage" class="page-close-box" @click="onCancel()">
        <img src="@/assets/img/back2.png" alt="">
      </label>
    </el-main>
  </el-container>
</template>

<script lang="ts">
export default {
  name: 'formClassAdvanceAI',
};
</script>

<script setup lang="ts">
import * as validateRules from '@/common/utils/validate';
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { StudentData } from '@/api/generated/studentController';
import { StudentClassData } from '@/api/generated/studentClassController';
import { CourseData } from '@/api/generated/courseController';
import { SysDeptData } from '@/api/generated/sysDeptController';
import { StudentController, StudentClassController, CourseController, SysDeptController } from '@/api/generated';
import FormEditClassAI from '@/pages/aiform/formEditClassAI.vue';
import FormAddClassAI from '@/pages/aiform/formAddClassAI.vue';
import DeptSelect from '@/components/DeptSelect/index.vue';
import UserSelect from '@/components/UserSelect/index.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const { 
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
  }>(),
  {
    subPage: 0,
  },
);

const formFilter = reactive({
  // 所属校区
  schoolId: undefined,
  // 班级名称
  classNameFilter: undefined,
  // 班级级别
  classLevelFilter: undefined,
  // 创建时间
  createTimeFilter: [],
});
const formFilterCopy = reactive({
  // 所属校区
  schoolId: undefined,
  // 班级名称
  classNameFilter: undefined,
  // 班级级别
  classLevelFilter: undefined,
  // 创建时间
  createTimeFilter: [],
});
const instance = getCurrentInstance();

const onCancel = () => {
  router.go(-1);
  layoutStore.removeCachePage(route.fullPath as string);
  route.meta.refreshParentCachedPage = true;
};

const onResume = () => {
  refreshFormClassAdvanceAI();
};
const schoolId = ref();
const refreshSchoolIdDropdownList = () => {
  schoolIdWidget.reloadDropdownData().then(dataList => {
    if (
      !Array.isArray(dataList) ||
      dataList.find(item => item.id === formFilter.schoolId) == null
    ) {
      formFilter.schoolId = undefined;
      formFilterCopy.schoolId = undefined;
    }
    if (schoolId.value) schoolId.value.setCurrentKey(formFilter.schoolId);
  });
};
/**
 * 所属校区下拉数据获取函数
 */
const loadSchoolIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictSysDept(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 所属校区选中值改变
 */
const onSchoolIdValueChange = (value) => {
  if (value.id !== formFilter.schoolId) {
    formFilter.schoolId = value.id;
  } else {
    formFilter.schoolId = undefined;
    nextTick(() => {
      schoolId.value?.setCurrentKey(null);
    });
  }
  refreshFormClassAdvanceAI(true);
};
// 所属校区配置参数
const schoolIdOptions: DropdownOptions<DictData> = {
  loadData: loadSchoolIdDropdownList,
  isTree: true,
};
// 所属校区下拉组件
const schoolIdWidget = useDropdown(schoolIdOptions);
const { dropdownList: schoolIdWidgetDropdownList } = schoolIdWidget
/**
 * 表格组件数据获取函数，返回Promise
 */
const loadStudentClassWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
  };
  return new Promise((resolve, reject) => {
    StudentClassController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadStudentClassVerify = () => {
  formFilterCopy.classNameFilter = formFilter.classNameFilter;
  formFilterCopy.classLevelFilter = formFilter.classLevelFilter;
  formFilterCopy.createTimeFilter = formFilter.createTimeFilter;
  formFilterCopy.schoolId = formFilter.schoolId;
  return true;
};
/**
 * 批量删除
 */
const onStudentClassSelectionChange = (values) => {
  studentClassBatchSelectRows.value = values || [];
};
const onAddStudentclassClick = () => {
  // 新建行内编辑数据
  const newRow = {
    // 班级Id
    classId: undefined,
    // 班级名称
    className: undefined,
    // 所属校区
    schoolId: undefined,
    // 班长
    leaderId: undefined,
    // 完成课时
    finishClassHour: undefined,
    // 班级级别
    classLevel: undefined,
    // 创建用户
    createUserId: undefined,
    // 班级创建时间
    createTime: undefined,
    // 班级状态(0: 正常 1: 解散)
    status: undefined,
  };
  studentClass.value.editRow(newRow, true);
};
/**
 * 新建班级
 */
const onFormAddClassAIClick = (row?: StudentClassData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建班级', FormAddClassAI, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      studentClassWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导入
 */
const onImportClick = (file) => {
  let params: ANY_OBJECT = {
    importFile: file.raw,
    // 是否忽略表头
    skipHeader: false
  };

  StudentClassController.import(params).then(res => {
    ElMessage.success('导入成功');
    studentClassWidget.refreshTable();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 导出
 */
const onExportClick = (row?: StudentClassData) => {
  let params: ANY_OBJECT = {
    studentClassDtoFilter: {
      className: formFilter.classNameFilter,
      schoolId: formFilter.schoolId,
      classLevel: formFilter.classLevelFilter,
      createTimeStart: Array.isArray(formFilter.createTimeFilter) ? formFilter.createTimeFilter[0] : formFilter.createTimeFilter,
      createTimeEnd: Array.isArray(formFilter.createTimeFilter) ? formFilter.createTimeFilter[1] : formFilter.createTimeFilter,
    }
  };

  StudentClassController.export(params, '表格组件.xlsx').then(res => {
    ElMessage.success('导出成功');
  }).catch(e => {
    ElMessage.error(e.errorMessage);
  });
};
/**
 * 批量删除
 */
const onBatchDeleteClick = (row?: StudentClassData) => {
  let params: ANY_OBJECT = {
  };

  ElMessageBox.confirm('是否删除选中数据？').then(res => {
    params.classIdList = studentClassBatchSelectRows.value.map(item => item.classId);
    StudentClassController.deleteBatch(params).then(res => {
      ElMessage.success('删除成功');
      studentClassBatchSelectRows.value = [];   
      studentClassWidget.refreshTable(true, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 编辑班级
 */
const onFormEditClassAIClick = (row?: StudentClassData) => {
  let params: ANY_OBJECT = {
    classId: row?.classId,
  };

  router.push({
    name: 'formEditClassAI',
    query: { ...params, subPage: true }
  });
};
const onEditStudentclassClick = (row?: StudentClassData) => {
  if (row == null) return;
  studentClass.value.editRow(row, false);
};
/**
 * 删除
 */
const onDeleteClick = (row?: StudentClassData) => {
  let params: ANY_OBJECT = {
    classId: row?.classId,
  };

  ElMessageBox.confirm('是否删除此班级？').then(res => {
    StudentClassController.delete(params).then(res => {
      ElMessage.success('删除成功');
      studentClassWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
const mergeStudentClassInlineRow = (row, rowCopy) => {
  row.className = rowCopy.className;
  row.schoolId = rowCopy.schoolId;
  row.schoolIdDictMap = rowCopy.schoolIdDictMap || {};
  row.classLevel = rowCopy.classLevel;
  row.classLevelDictMap = rowCopy.classLevelDictMap || {};
  row.totalClassHours = rowCopy.totalClassHours;
  row.createTime = rowCopy.createTime;
};
const onSaveStudentClassInlineRow = (row, autoEditNext) => {
  if (studentClass.value != null) {
    studentClass.value
      .saveRow(autoEditNext)
      .then(res => {
        let { rowData, nextRow, isNew, isDirty } = res;
        let params = {
          studentClassDto: {
            ...rowData
          }
        };
        if (isNew) {
          // 新建数据
          StudentClassController.add(params)
            .then(res => {
              ElMessage.success('保存成功');
              studentClassWidget.refreshTable(false);
            })
            .catch(e => {
              console.log(e);
            });
          return;
        }
        if (!isNew) {
          // 保存数据
          if (!isDirty) {
            // 未修改数据
            if (autoEditNext) {
              if (nextRow == null) {
                nextRow = studentClassWidgetDataList[0];
              }
              onEditStudentclassClick(nextRow);
            } else {
              onCancelStudentClassInlineRow(row);
            }
          } else {
            // 行数据已经修改
            StudentClassController.update(params)
              .then(res => {
                ElMessage.success('保存成功');
                studentClassWidget.refreshTable(false);
              })
              .catch(e => {
                console.log(e);
              });
          }
        }
      })
      .catch(e => {
        if (e != null) {
          if (e != null && e.message != null && e.message !== '') {
            const firstField = 'studentClass' + stringCase(e.message, 1);
            const proxy = instance?.proxy;
            if (proxy != null) {
              if (proxy.$refs[firstField] && proxy.$refs[firstField].focus != null) proxy.$refs[firstField].focus();
            }
          }
        }
      });
  }
};
const onCancelStudentClassInlineRow = (row, deleteRow = true) => {
  if (studentClass.value != null) {
    studentClass.value.cancelEditRow(deleteRow);
  }
};
// 表格组件表格组件参数
const studentClassOptions: TableOptions<StudentClassData> = {
  loadTableData: loadStudentClassWidgetData,
  verifyTableParameter: loadStudentClassVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: 'createTime',
  ascending: true,
};
// 批量选中数据
const studentClassBatchSelectRows = ref<StudentClassData[]>([]);
const studentClassInline = ref({
  // 行内编辑校验规则
  inlineRules: {
  },
  // 是否支持自动编辑下一行
  supportAutoNext: true
});
// 行内编辑列录入组件引用
// 表格组件表格组件
const studentClass = ref();
const studentClassWidget = useTable(studentClassOptions);
const {
  dataList: studentClassWidgetDataList,
  currentPage: studentClassWidgetCurrentPage,
  pageSize: studentClassWidgetPageSize,
  totalCount: studentClassWidgetTotalCount,
} = studentClassWidget;
/**
 * 班级级别下拉数据获取函数
 */
const loadClassLevelFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'ClassLevel', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 班级级别配置参数
const classLevelFilterOptions: DropdownOptions<DictData> = {
  loadData: loadClassLevelFilterDropdownList,
  isTree: false,
};
// 班级级别下拉组件
const classLevelFilterWidget = useDropdown(classLevelFilterOptions);
const { dropdownList: classLevelFilterWidgetDropdownList } = classLevelFilterWidget
const refreshFormClassAdvanceAI = () => {
  // 刷新段落
  studentClassWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormClassAdvanceAI = () => {
  formFilter.classNameFilter = undefined;
  formFilterCopy.classNameFilter = undefined;
  formFilter.classLevelFilter = undefined;
  formFilterCopy.classLevelFilter = undefined;
  formFilter.createTimeFilter = undefined;
  formFilterCopy.createTimeFilter = undefined;
  formFilter.schoolId = undefined;
  formFilterCopy.schoolId = undefined;
  refreshFormClassAdvanceAI();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormClassAdvanceAI();
};
const formInit = () => {
  classLevelFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  schoolIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormClassAdvanceAI();
};

onMounted(() => {
  formInit();
});

onActivated(() => {
  onResume();
});
</script>

<style scoped>
  ::v-deep .el-tree-node__content {
    height: 35px;
  }
</style>
